//
//  SCContentLabel.swift
//  weibo
//
//  Created by 阿城 on 15/12/18.
//  Copyright © 2015年 阿城. All rights reserved.
//

import UIKit

class SCContentLabel: UILabel {

    var linkResults: [SCMatchResult]?
    private var linkViews = [UIView]()
    
    override var attributedText: NSAttributedString?{
        didSet{
            textView.attributedText = attributedText
            textView.font = UIFont.systemFontOfSize(kStatusFont)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        userInteractionEnabled = true
        addSubview(textView)
//        textView.userInteractionEnabled = false
        textView.alpha = 0
//        textView.editable = false
        textView.scrollEnabled = false
        textView.textContainerInset = UIEdgeInsetsMake(0, -5, 0, -5)
//        textView.contentInset = UIEdgeInsetsMake(0, -5, 0, -5)

        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(UIEdgeInsetsZero)
        }
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let point = touches.first!.locationInView(textView)
        
        //转换
        textView.selectedTextRange = textView.characterRangeAtPoint(point)
        let range = textView.selectedRange
        
//        printLog(range)
        
        if linkResults == nil{
            return
        }

        for result in linkResults!{
            if NSLocationInRange(range.location, result.range){
//                printLog(result.range)
                textView.selectedRange = result.range
                let rects = textView.selectionRectsForRange(textView.selectedTextRange!)
//                printLog(rects)
                
                for value in rects {
                    let rect = value as! UITextSelectionRect
                    let v = UIView(frame: rect.rect)
//                    printLog(rect.rect)
                    v.layer.cornerRadius = 3
                    v.layer.masksToBounds = true
                    v.backgroundColor = SCColor.getColor(177, G: 215, B: 255)
                    insertSubview(v, atIndex: 0)
                    linkViews.append(v)
                }
                
            }
        }
        
    }
    
    // 在用户手指离开的时候移除高亮
    override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
        for v in linkViews {
            v.removeFromSuperview()
        }
        linkViews.removeAll()
    }
    
    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        touchesCancelled(touches, withEvent: event)
    }
    
    
    private lazy var textView = UITextView()
    
}
